package team.first.movieapiv2.util;
import com.mongodb.*;
import com.mongodb.client.MongoClients;
import dev.morphia.Datastore;
import dev.morphia.Morphia;

import java.util.Arrays;

/**
 * @Author: HAPPY
 * @Project_name: project
 * @Package_name: team.first.movieapiv2.util
 * @Date: 2021/12/9 10:49
 * @Description:
 */
public class MongoDBUtil {
    public static final String MONGO_DB_NAME = "movie_db";
    public static final String MONGO_DB_USERNAME = "user";
    public static final String MONGO_DB_PASSWORD = "123456";


    public static DBCollection getCollection(String collectionName) {
        MongoClient mongoClient = new MongoClient( "162.14.114.84" , 26024);//建立连接
        DB get_db_credit = mongoClient.getDB("movie_db");//数据库名
        return get_db_credit.getCollection(collectionName);//集合名，对应mysql中的表名
    }

    public static Datastore getDataStore() {
        ServerAddress serverAddress = new ServerAddress("162.14.114.84", 26024);

        // Mongo数据库的认证信息
        MongoCredential mongoCredential = MongoCredential.createCredential(MONGO_DB_USERNAME, MONGO_DB_NAME,
                MONGO_DB_PASSWORD.toCharArray());
        MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
                .applyToClusterSettings(builder ->
                        builder.hosts(Arrays.asList(serverAddress)))
                .credential(mongoCredential).build();

        // MongoClient必须是com.mongodb.client.MongoClient
        com.mongodb.client.MongoClient mongoClient = MongoClients.create(mongoClientSettings);
        return Morphia.createDatastore(mongoClient, MONGO_DB_NAME);
    }
}
